import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.atomic.AtomicInteger;

public class TimeServerHandler extends ChannelInboundHandlerAdapter {

    private AtomicInteger atomicInteger = new AtomicInteger();


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channelRegistered");
        super.channelRegistered(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        try {
            // 这里已经是解码成功的消息
            String body = (String) msg;
            System.out.println(atomicInteger.addAndGet(1) + "--->" + Thread.currentThread().getName() + ", The server receive order : " + body);

            String respMsg = "I'm server , 接受消息成功！" + Thread.currentThread().getName() + System.getProperty("line.separator");
            ByteBuf byteBuf = Unpooled.copiedBuffer(respMsg.getBytes());
            // 每次写的时候同时刷新，放止Tcp粘包
            ctx.writeAndFlush(byteBuf);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("-----客户端关闭:" + ctx.channel().remoteAddress());
        ctx.close();
    }
}
